/*****************************************************************************
 *  CommLayerLib for J2ME - BluetoothLayer.java
 *  Copyright (C) 2012  Matteo Piscitelli
 *  E-mail: matteo@picciux.it
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *  For further info, check http://code.google.com/p/java-comm-layer/
 *
 *  SVN: $Id: BluetoothLayer.java 40 2012-10-10 19:54:31Z picciux@gmail.com $
 *  
 *****************************************************************************/

package it.picciux.commlayer.j2me.bluetooth;

import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.microedition.io.StreamConnection;

import it.picciux.commlayer.CommLayerException;

public class BluetoothLayer extends
		it.picciux.commlayer.bluetooth.BluetoothLayer
							implements DiscoveryListener {

	private LocalDevice lDev;
	private RemoteDevice rDev;
	private DiscoveryAgent dAgent;
	private RemoteDevice[] devsDiscovered;

	private String connURL;
	private String searchDeviceAddress;

	private int operation = OPERATION_NONE;

	private BTDeviceSearch searchHelper = null;
	private BTDevice inquiryDevice = null;
	
	private final static int L2CAP_UUID 			= 0x0100;
	private final static int RFCOMM_UUID 			= 0x0003;
	
	private final static int OPERATION_NONE = 0;
	private final static int OPERATION_PORTSCAN = 1;
	private final static int OPERATION_CONNECT = 2;

	private final static int INQUIRY_DEV_TID = -20;
	
	private StreamConnection connection = null;
	
	private final static boolean DEBUG = true;

	
	public BluetoothLayer() {
		this.devsDiscovered = new RemoteDevice[0];
	}

	public boolean scan() {
		System.out.println("PortScan starting...");
		
		operation = OPERATION_PORTSCAN;
		
		try {
			discover(null);
		} catch (CommLayerException e) {
			notifyListeners(PORTSCAN_ERROR, e.getMessage());
			System.out.println("Portscan error: " + e.getMessage());
			return false;			
		}
		
		notifyListeners(PORTSCAN_STARTED);
		System.out.println("PortScan started");
		return true;
	}

	/* (non-Javadoc)
	 * @see it.picciux.commlayer.CommLayer#cancelScan()
	 */
	public void cancelScan() {
		if (dAgent != null)
			dAgent.cancelInquiry(this);
	}

	public void deviceDiscovered(RemoteDevice arg0, DeviceClass arg1) {
		// TODO Auto-generated method stub
		
	}

	public void inquiryCompleted(int arg0) {
		// TODO Auto-generated method stub
		
	}

	public void serviceSearchCompleted(int arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}

	public void servicesDiscovered(int arg0, ServiceRecord[] arg1) {
		// TODO Auto-generated method stub
		
	}

	// bluetooth operations
	private void discover(String devAddress) throws CommLayerException {
		searchDeviceAddress = devAddress;
		
		if (searchDeviceAddress != null) rDev = null;
		
		try {
			lDev = LocalDevice.getLocalDevice();
		} catch (BluetoothStateException e) {
			lDev = null;
			dAgent = null;
			throw new CommLayerException(e.getMessage(), BLUETOOTH_NOT_AVAIL);
			//return false;
		}
		
		dAgent = lDev.getDiscoveryAgent();

		int maxSearches = Integer.parseInt(LocalDevice.getProperty("bluetooth.sd.trans.max"));

		if (DEBUG) System.out.println(maxSearches + " max searches");
		searchHelper = new BTDeviceSearch(maxSearches);
		
		RemoteDevice[] remDevs = null;
		
		if (devAddress != null) {
			//remDevs = dAgent.retrieveDevices(DiscoveryAgent.CACHED);
		}
		
		if (remDevs == null) {
			if (DEBUG) System.out.println("No cached devices");
			
			if (devAddress != null) {
				//remDevs = dAgent.retrieveDevices(DiscoveryAgent.PREKNOWN);
			}
		}
				
		if (remDevs == null) {
			if (DEBUG) System.out.println("No preknown devices: start inquiry");
			
			try {
				inquiryDevice = searchHelper.addDevToScan(null);
				inquiryDevice.transID = INQUIRY_DEV_TID;
				dAgent.startInquiry(DiscoveryAgent.GIAC, this); // start inquiry
			} catch (BluetoothStateException e) {
				if (DEBUG) System.out.println("Inquiry failed!");
				throw new CommLayerException(e.getMessage(), BLUETOOTH_NOT_AVAIL);
				//return false;
			}
		}
			
		//return true;
	}

	protected void tryConnection() throws CommLayerException {
		// TODO Auto-generated method stub
	}

	protected void doDisconnect() {
		// TODO Auto-generated method stub
	}

	protected void setConnectThread(Thread thread) {
	}
	
	
}
